package middle;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Solution_39 {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        List<List<Integer>> res = new ArrayList<>();
        dps(candidates, res, new ArrayList<>(), target, 0);
        return res;
    }

    private void dps(int[] candidates, List<List<Integer>> res, List<Integer> list, int sub, int index) {
        if (sub == 0) {
            res.add(new ArrayList<>(list));
        }
        for (int i = index; i < candidates.length; i++) {
            int candidate = candidates[i];
            if (candidate <= sub) {
                list.add(candidate);
                dps(candidates, res, list, sub - candidate, i);
                list.remove(list.size() - 1);
            }
        }
    }

    public static void main(String[] args) {
        Solution_39 model = new Solution_39();
//        List<List<Integer>> list = model.combinationSum(new int[]{2,3,6,7}, 7);
//        List<List<Integer>> list = model.combinationSum(new int[]{2,3,5}, 8);
        List<List<Integer>> list = model.combinationSum(new int[]{2}, 1);
        for (List<Integer> integers : list) {
            System.out.println(integers);
        }
    }
}
